package client.comm.commlib.utils

import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import client.comm.commlib.ContextProvider

object SharedUtil {

    /**
     * 存储boolean类型的键值对到SharedPreferences文件当中。
     * @param key
     * 存储的键
     * @param value
     * 存储的值
     */
    fun save(key: String, value: Any) {

        ContextProvider.get().shared?.run {
            edit().run {
                if (value is Int) {
                    putInt(key, value).apply()
                } else if (value is Float) {
                    putFloat(key, value).apply()
                } else if (value is String) {
                    putString(key, value).apply()
                } else if (value is Long) {
                    putLong(key, value).apply()
                } else if (value is Boolean) {
                    putBoolean(key, value).apply()
                }
            }
        }


    }

    fun read(key: String, defValue: Boolean): Boolean {
        if (ContextProvider.get().shared != null) {
            return ContextProvider.get().shared!!.getBoolean(key, defValue)
        }
        return defValue
    }

    fun read(key: String, defValue: String? = ""): String? {
        if (ContextProvider.get().shared != null) {
            return ContextProvider.get().shared!!.getString(key, defValue)
        }
        return defValue
    }

    fun read(key: String, defValue: Long = 0.toLong()): Long {
        if (ContextProvider.get().shared != null) {
            return ContextProvider.get().shared!!.getLong(key, defValue)
        }
        return defValue
    }

    fun read(key: String, defValue: Float = 0.toFloat()): Float {
        if (ContextProvider.get().shared != null) {
            return ContextProvider.get().shared!!.getFloat(key, defValue)
        }
        return defValue
    }

    fun read(key: String, defValue: Int = 0): Int {
        if (ContextProvider.get().shared != null) {
            return ContextProvider.get().shared!!.getInt(key, defValue)
        }
        return defValue
    }

    fun contains(key: String): Boolean {
        var tmp: Boolean = false
        ContextProvider.get().shared?.run {
            tmp = contains(key)
        }
        return tmp
    }

    fun clear(key: String) {
        ContextProvider.get().shared?.run {
            edit().remove(key).apply()
        }
    }

    fun clearAll() {
        ContextProvider.get().shared?.run {
            edit().clear().apply()
        }
    }


}